package cn.edu.zjut.medlinebackend.service.impl;

import lombok.AllArgsConstructor;
import net.sourceforge.tess4j.*;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@AllArgsConstructor
public class OcrServiceImpl {

    private final Tesseract tesseract;

    /**
     * 识别图片中的文字
     * @param imageFile 图片文件
     * @return 文字信息
     */
    public String recognizeText(File imageFile) throws TesseractException, IOException {
        // 对图片进行文字识别
        tesseract.setLanguage("eng+chi_sim");
        String msg= tesseract.doOCR(imageFile);
        StringBuilder ocrformat = new StringBuilder();
        for (int i = 0; i < msg.length(); i++) {
            char c = msg.charAt(i);
            if (c == ' ' || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ) {
                if((i>=1 && i<=msg.length()-1)&&(msg.charAt(i-1)==' '&& msg.charAt(i+1)==' ')||(i==0)&&msg.charAt(i+1)==' '||(i==msg.length()-1)&&msg.charAt(i-1)==' ')
                    continue;
                ocrformat.append(c);
            }
            else if(c >= '\u4e00' && c <= '\u9fff'){
                ocrformat.append(c);
            }
        }
        return ocrformat.toString();
    }
}